using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Markup;
using Rhizome.Contract.Diag;
using Rhizome.Internal;
using Rhizome.Model.Validation;

namespace Rhizome.Model
{
	[ContentProperty("States")]
	public sealed class CriterionTransition : TransitionBase, IValidate
	{
		public CriterionTransition()
		{
			States = new RhizomeElementCollection<CriterionState>(this);
		}

		public object FailState { get; set; }

		public Collection<CriterionState> States { get; private set; }

		#region Implementation of IValidate

		IEnumerable<IValidationResult> IValidate.GetValidationResults()
		{
			if (FailState == null) yield return ValidationResult.FailStateNotSet;
			if (States.Any() == false) yield return ValidationResult.StatesAreEmpty;
		}

		#endregion

		#region Overrides of RhizomeElement

		protected override IEnumerable<IEnumerable> GetElementCollections()
		{
			return base.GetElementCollections().Concat(new[] {States});
		}

		#endregion

		public override object GetTransitionState()
		{
			var state = States.FirstOrDefault(s => s.Criterion.Test());
			if (state == null)
			{
				return FailState;
			}

			return state.State;
		}
	}
}